Computer Programming web Web programming Tips



The Insertion Sort - C++ source code

By Sergey Skudaev



Precondition: The function accepts an unsorted array and integer size that is the size of the array.

Post condition: Sorted array

#include "stdafx.h"
#include<iostream.h>

int* insertionSort ( int size, int array[]);
void exchange (int array[], int a, int b);


int main(int argc, char* argv[])
{
int array[10];
int i=0;

 while (i < 10)
{
cout<<"Please enter a number."<<endl;
cin>>array[i];
i++;

}
				cout<<"Unsorted array:"<<endl;
				for(int k=0; k<10;k++)
                                   cout<<array[k];
				cout<<endl;

 //call the sorting function
 int* arr=insertionSort(i,array);

				cout<<"Sorted array:"<<endl;
				for(int n=0; n<10;n+)
                                   cout<<arr[n];
				cout<<endl;
return 0;
}



int* insertionSort(int size, int array[])
{
    int current = 1;
    int temp;
    int walker;
	 int* pointer;
	 pointer=array;


        while (current < size)
        {
          temp = array [current];
          walker = current -1;


                while (( walker >= 0 )&&( temp < array [walker] ))
                {
                array[walker +1] = array[walker];
                walker = walker -1;
                }

            array [walker+1] = temp;
            current = current + 1;
         }

		return pointer;

}


My eBooks on Amazon.com

US    UK    BR    CA
US    UK    BR    CA
US   UK   BR   CA